package cn.liit.weixin.message.process.receive;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

import cn.liit.weixin.message.model.req.BaseEventMessage;
import cn.liit.weixin.message.model.req.ReqBaseMessage;

/**
 * 请求消息处理器管理类
 * @author zhangboqi
 *
 */
public class ReceiveProcessorManager {
	private static Map<String, ReceiveProcessor> baseMsgProcessorMap = new ConcurrentHashMap<>();
    private static Map<String, ReceiveProcessor> eventMsgProcessorMap = new ConcurrentHashMap<>();
    public static final String UNSUPPORTED_MES_TYPE="unsupported";
    
	/**
     * 注销消息执行器
     * @param receiveProcessor
     */
    public static void unregisterMsgProcessor(ReceiveProcessor receiveProcessor) {
        String msgType = receiveProcessor.msgType();
        if ("event".equals(msgType)) {
            eventMsgProcessorMap.remove(receiveProcessor.event());
        } else {
            baseMsgProcessorMap.remove(msgType);
        }
    }

    /**
     * 注册消息执行器
     * @param receiveProcessor
     */
    public static void registerMsgProcessor(ReceiveProcessor receiveProcessor) {
        String msgType = receiveProcessor.msgType();
        if ("event".equals(msgType)) {
            eventMsgProcessorMap.put(receiveProcessor.event(), receiveProcessor);
        } else {
            baseMsgProcessorMap.put(msgType, receiveProcessor);
        }
    }

    private static ReceiveProcessor getMsgProcessor(String msgType, String event) {
    	ReceiveProcessor receiveProcessor;
        if ("event".equals(msgType) && event != null) {
            receiveProcessor = eventMsgProcessorMap.get(event);
        } else {
            receiveProcessor = baseMsgProcessorMap.get(msgType);
        }
        if (receiveProcessor == null) {
            receiveProcessor = baseMsgProcessorMap.get(ReceiveProcessorManager.UNSUPPORTED_MES_TYPE);
        }

        return receiveProcessor;
    }

    private static ReceiveProcessor getMsgProcessor(Map map) {
        String msgType = (String) map.get("msgType");
        String event = null;
        if ("event".equals(msgType)) {
            event = (String) map.get("event");
        }
        return getMsgProcessor(msgType, event);
    }

    public static ReceiveProcessor getMsgProcessor(ReqBaseMessage receiveReqData) {
        String msgType = receiveReqData.getMsgType();
        String event = null;
        if ("event".equals(msgType) && receiveReqData instanceof BaseEventMessage) {
            event = ((BaseEventMessage) receiveReqData).getEvent();
        }
        return getMsgProcessor(msgType, event);
    }
}
